"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

require("antd/lib/button/style/css");

var _button = _interopRequireDefault(require("antd/lib/button"));

require("antd/lib/checkbox/style/css");

var _checkbox = _interopRequireDefault(require("antd/lib/checkbox"));

require("antd/lib/row/style/css");

var _row = _interopRequireDefault(require("antd/lib/row"));

require("antd/lib/date-picker/style/css");

var _datePicker = _interopRequireDefault(require("antd/lib/date-picker"));

require("antd/lib/input/style/css");

var _input = _interopRequireDefault(require("antd/lib/input"));

require("antd/lib/col/style/css");

var _col = _interopRequireDefault(require("antd/lib/col"));

require("antd/lib/form/style/css");

var _form = _interopRequireDefault(require("antd/lib/form"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _icons = require("@ant-design/icons");

var _classnames = _interopRequireDefault(require("classnames"));

var _moment = _interopRequireDefault(require("moment"));

var _selectCustom = _interopRequireDefault(require("../../input/selectCustom"));

var _utils = require("../../utils/utils");

var _events = _interopRequireDefault(require("../../utils/events"));

var _util = require("../util");

require("./filter.less");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var FormItem = _form.default.Item;
var formItemLayout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
};
var formItemLayoutDate = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 17
  },
  style: {
    position: 'relative',
    left: '-12.8%',
    width: '115%'
  }
}; // 一个计数器

var num = function num() {
  var mas = 0;
  return {
    clear: function clear() {
      mas = 0;
      return this;
    },
    add: function add(item) {
      if (item.inputType === 'dataRange') {
        mas += 12;
      } else if (item.inputType === 'checkBox') {
        mas += 3;
      } else {
        mas += 6;
      }

      return mas;
    },
    getNum: function getNum() {
      return mas;
    }
  };
}; // 该过滤是控制展开收起,最终获取要展示的列表数据


var getShowcolumns = function getShowcolumns(columnsList, open) {
  var numObj = num().clear();
  var max = 18; // 计数到18即为一行

  var columns = columnsList.filter(function (i) {
    return i.show;
  }); // 如果是展开，直接返回

  if (open) {
    return columns;
  }

  var list = []; // 待显示的列表

  for (var i = 0; i < columns.length; i += 1) {
    numObj.add(columns[i]);

    if (columns[i].show && numObj.getNum() <= max) {
      list.push(columns[i]);
    }
  }

  return list;
};

var Filter = function Filter(props) {
  // 是否隐藏多余输入框
  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      open = _useState2[0],
      setOpen = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      columns = _useState4[0],
      setColumns = _useState4[1];

  var _props$defaultConditi = props.defaultCondition,
      defaultCondition = _props$defaultConditi === void 0 ? {} : _props$defaultConditi,
      columnsFilter = props.columnsFilter,
      submitPreMiddleware = props.submitPreMiddleware,
      onReset = props.onReset,
      onSearch = props.onSearch;
  var formRef = (0, _react.useRef)();

  var onOpenClick = function onOpenClick() {
    setOpen(!open);
  }; // 获取所有数据


  var getValues = (0, _react.useCallback)(function () {
    var values = formRef.current.getFieldsValue();
    var valuesKey = Object.keys(values);

    for (var i = 0; i < valuesKey.length; i += 1) {
      if (values[valuesKey[i]] && values[valuesKey[i]].valueOf) {
        // 日期转化为时间戳
        values[valuesKey[i]] = values[valuesKey[i]].valueOf();
      }
    } // 日期输入反了，自动给他调过开


    columns.forEach(function (i) {
      if (i.inputType === 'dataRange' && i.value.length && i.value.length === 2) {
        // 开始调整日期
        if (values[i.value[0]] && values[i.value[1]] && Number(values[i.value[0]]) > Number(values[i.value[1]])) {
          var _formRef$current$setF;

          var a = values[i.value[0]];
          values[i.value[0]] = values[i.value[1]];
          values[i.value[1]] = a;
          formRef.current.setFieldsValue((_formRef$current$setF = {}, _defineProperty(_formRef$current$setF, i.value[0], (0, _moment.default)(new Date(values[i.value[0]]))), _defineProperty(_formRef$current$setF, i.value[1], (0, _moment.default)(new Date(values[i.value[1]]))), _formRef$current$setF));
        }
      }
    });

    if (submitPreMiddleware) {
      // 暴露一个外部可以处理参数的接口
      values = submitPreMiddleware(values);
    }

    return _objectSpread(_objectSpread({}, defaultCondition), values);
  }, [formRef.current, columns, submitPreMiddleware, defaultCondition]);
  var onAdvancedSearchSubmit = (0, _react.useCallback)(function () {
    var values = getValues();
    onSearch(values);
  }, [getValues]);
  var onAdvancedSearchReset = (0, _react.useCallback)(function () {
    formRef.current.resetFields(); // const values = this.getValues();

    var parms = {};

    if (onReset) {
      onReset(parms);
    }
  }, [formRef]); // 放开对表格对控制

  (0, _react.useEffect)(function () {
    var userAction = {
      getValues: getValues
    };
    var ref = props.ref;

    if (ref && typeof ref !== 'function') {
      ref.current = userAction;
    }
  }, [getValues]); // 监听数据变化

  (0, _react.useEffect)(function () {
    setColumns((0, _util.getList)(columnsFilter));
  }, [columnsFilter]); // 监听表单设置修改后，重新渲染

  (0, _react.useEffect)(function () {
    var pathname = window.location.pathname;

    _events.default.addListener("".concat(pathname, "=refresh"), function () {
      setColumns((0, _util.getList)(columnsFilter));
    });
  }, []); // 渲染lable

  var labelRender = function labelRender(item) {
    if (item.labelRender) {
      // Render优先
      return item.labelRender;
    }

    var text = item.label;

    if (text && text.length > 5) {
      // 让他小一点
      return /*#__PURE__*/_react.default.createElement("span", {
        style: {
          fontSize: '10px'
        }
      }, text);
    }

    return text;
  };

  var list = getShowcolumns(columns, open);
  var numObj = num().clear();
  var showList = columns.filter(function (item) {
    return item.show;
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)('filter', 'xuanyue-filter')
  }, /*#__PURE__*/_react.default.createElement(_form.default, {
    ref: formRef
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "dashed"
  }, /*#__PURE__*/_react.default.createElement(_row.default, {
    gutter: 24
  }, list.map(function (i, index) {
    numObj.add(i);
    var content = false;

    if (i.render) {
      content = /*#__PURE__*/_react.default.createElement(_col.default, {
        // style={{ height: '48px' }}
        span: i.inputType === 'dataRange' ? 12 : 6,
        key: i.label
      }, i.render(FormItem, i.inputType === 'dataRange' ? formItemLayoutDate : formItemLayout, defaultCondition));
    } else if (i.inputType === 'code') {
      content = /*#__PURE__*/_react.default.createElement(_col.default, {
        span: 6,
        key: i.label
      }, /*#__PURE__*/_react.default.createElement(FormItem, _extends({}, formItemLayout, {
        label: labelRender(i),
        name: i.value,
        initialValue: defaultCondition[i.value],
        getValueFromEvent: _utils.inputTrim
      }), /*#__PURE__*/_react.default.createElement(_input.default, {
        placeholder: "\u8BF7\u8F93\u5165"
      })));
    } else if (i.inputType === 'text') {
      content = /*#__PURE__*/_react.default.createElement(_col.default, {
        span: 6,
        key: i.label
      }, /*#__PURE__*/_react.default.createElement(FormItem, _extends({}, formItemLayout, {
        label: labelRender(i),
        name: i.value,
        initialValue: defaultCondition[i.value],
        getValueFromEvent: _utils.inputTrim
      }), /*#__PURE__*/_react.default.createElement(_input.default, {
        placeholder: "\u8BF7\u8F93\u5165"
      })));
    } else if (i.inputType && i.inputType.split(',')[0] === 'select') {
      content = /*#__PURE__*/_react.default.createElement(_col.default, {
        span: 6,
        key: i.label
      }, /*#__PURE__*/_react.default.createElement(FormItem, _extends({}, formItemLayout, {
        label: labelRender(i),
        name: i.value,
        initialValue: defaultCondition[i.value]
      }), /*#__PURE__*/_react.default.createElement(_selectCustom.default, {
        optionList: i.listArr || [],
        keyValue: i.keyValue || ['name', 'id'],
        mode: i.inputType.split(',')[1] || '' // extraObject={{
        //   id: currentItem.cooperativePartnerId,
        //   name: currentItem.cooperativePartnerName,
        // }}

      })));
    }
    /* else if (i.inputType === 'cascaderProduct') {
      content = (
        <Col span={6} key={i.label}>
          <FormItem {...formItemLayout} label={this.labelRender(i)}>
            {getFieldDecorator(i.value, {
              initialValue: defaultConditon[i.value],
            })(
              <ProductCategoryCascader
                productList={i.listArr || props.preThis.props[props.type][i.listName]}
              />
            )}
          </FormItem>
        </Col>
      );
    } */
    else if (i.inputType === 'dataRange') {
        content = /*#__PURE__*/_react.default.createElement(_col.default, {
          span: 12,
          key: i.label,
          style: {
            overflow: 'hidden'
          }
        }, /*#__PURE__*/_react.default.createElement(FormItem, _extends({}, formItemLayoutDate, {
          label: labelRender(i)
        }), /*#__PURE__*/_react.default.createElement(_row.default, null, /*#__PURE__*/_react.default.createElement(_col.default, {
          span: 11
        }, /*#__PURE__*/_react.default.createElement(FormItem, {
          name: i.value[0],
          initialValue: defaultCondition[i.value[0]] ? (0, _moment.default)(new Date(defaultCondition[i.value[0]])) : undefined
        }, /*#__PURE__*/_react.default.createElement(_datePicker.default, {
          style: {
            width: '100%'
          },
          format: "YYYY/MM/DD"
        }))), /*#__PURE__*/_react.default.createElement(_col.default, {
          span: 2,
          style: {
            textAlign: 'center',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }
        }, "~"), /*#__PURE__*/_react.default.createElement(_col.default, {
          span: 11
        }, /*#__PURE__*/_react.default.createElement(FormItem, {
          name: i.value[1],
          initialValue: defaultCondition[i.value[1]] ? (0, _moment.default)(new Date(defaultCondition[i.value[1]])) : undefined
        }, /*#__PURE__*/_react.default.createElement(_datePicker.default, {
          style: {
            width: '100%'
          },
          format: "YYYY/MM/DD"
        }))))));
      } else if (i.inputType === 'checkBox') {
        content = /*#__PURE__*/_react.default.createElement(_col.default, {
          span: 3,
          style: {
            paddingLeft: 0,
            paddingRight: 0,
            position: 'relative',
            left: '3%'
          }
        }, /*#__PURE__*/_react.default.createElement(FormItem, {
          valuePropName: "checked",
          name: i.value,
          initialValue: defaultCondition[i.value]
        }, /*#__PURE__*/_react.default.createElement(_checkbox.default, null, i.label)));
      }

    if (numObj.getNum() === 24 || numObj.getNum() === 21 || numObj.getNum() === 18 && list[index + 1] && list[index + 1].inputType === 'dataRange') {
      numObj.clear();
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, content, /*#__PURE__*/_react.default.createElement(_col.default, {
        span: 24
      }));
    }

    return content;
  }), /*#__PURE__*/_react.default.createElement(_col.default, {
    className: "textRight",
    style: {
      float: 'right',
      marginTop: '-1px',
      marginLeft: 'auto',
      marginBottom: 12
    }
  }, /*#__PURE__*/_react.default.createElement(_button.default, {
    style: {
      marginRight: '8px'
    },
    type: "primary",
    onClick: onAdvancedSearchSubmit,
    htmlType: "submit"
  }, "\u67E5\u8BE2"), /*#__PURE__*/_react.default.createElement(_button.default, {
    onClick: onAdvancedSearchReset
  }, "\u91CD\u7F6E"), /*#__PURE__*/_react.default.createElement("a", {
    style: {
      marginLeft: '8px',
      display: showList.length <= 2 ? 'none' : ''
    },
    onClick: onOpenClick
  }, open ? '收起' : '展开', open ? /*#__PURE__*/_react.default.createElement(_icons.UpOutlined, {
    style: {
      marginLeft: '4px'
    }
  }) : /*#__PURE__*/_react.default.createElement(_icons.DownOutlined, {
    style: {
      marginLeft: '4px'
    }
  })))))));
};

Filter.propTypes = {
  columnsFilter: _propTypes.default.array,
  defaultCondition: _propTypes.default.object,
  onSearch: _propTypes.default.func,
  onReset: _propTypes.default.func,
  submitPreMiddleware: _propTypes.default.func,
  // 暴露一个外部可以处理参数的接口
  iconStyle: _propTypes.default.object
};
var _default = Filter;
exports.default = _default;